package com.manning.readinglist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
@EnableWebSecurity//实际上间接创建了一个websecurityconfiguration的bean，所以在应用级配置后的自动配置时
// ，这个bean已经存在，自动配置类的@conditionalonmissingbean不成立，spirngboot提供的配置失效，从而实现覆盖

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ReaderRepository readerRepository;
    @Override
    protected void configure(HttpSecurity httpSecurity) throws  Exception{
        httpSecurity.authorizeRequests()//http验证
                .antMatchers("/").access("hasRole('READER')")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true");
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
//        在进行认证的时候需要一个 UserDetailsService 来获取用户的信息 UserDetails
       auth.userDetailsService(new UserDetailsService() {
           @Override
           public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
               return readerRepository.findById(s).orElse(null);
           }
       });

    }
}
